package com.biscuit.page.basicservice.conf.handler;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.biscuit.page.basicservice.model.context.UserContext;
import com.biscuit.page.basicservice.model.entities.mysql.SysUser;
import com.biscuit.page.basicservice.model.entities.mysql.SysUserDetail;
import com.biscuit.page.basicservice.model.enums.BaseResponseEnum;
import com.biscuit.page.basicservice.utils.BaseExceptionUtil;

import java.util.Objects;

/**
 * @author biscuit
 * @createTime 2024/6/25 20:29
 */
public class UserContextHandler {

    private static final ThreadLocal<UserContext> LOCAL = new ThreadLocal<>();

    private static UserContext getData() {
        UserContext userContext = LOCAL.get();
        if (Objects.isNull(userContext)) {
            userContext = new UserContext();
            LOCAL.set(userContext);
        }

        return userContext;
    }


    public static UserContext getContext() {
        BaseExceptionUtil.throwException(Objects.nonNull(LOCAL.get()), "用户未登录", BaseResponseEnum.ERROR_UNAUTHORIZED);
        return LOCAL.get();
    }

    public static String getAuthorization() {
        return getContext().getAuthorization();
    }

    public static Long getUserId() {
        BaseExceptionUtil.throwException(Objects.nonNull(getContext().getUser()), "用户未登录", BaseResponseEnum.ERROR_UNAUTHORIZED);
        return getContext().getUser().getId();
    }

    public static Long getUserIdOr0() {
        try {
            return getUserId();
        } catch (Exception e) {
            return 0L;
        }
    }

    public static String getUserUid() {
        BaseExceptionUtil.throwException(Objects.nonNull(getContext().getUser()), "用户未登录", BaseResponseEnum.ERROR_UNAUTHORIZED);
        return getContext().getUser().getUId();
    }

    public static void setContext(SysUser sysUser) {
        setContext(null, sysUser, null);
    }

    public static void setContext(SysUserDetail sysUserDetail) {
        setContext(null, null, sysUserDetail);
    }

    public static void setAuthorization(String authorization) {
        setContext(authorization, null, null);
    }

    public static void setContext(String authorization, SysUser sysUser, SysUserDetail sysUserDetail) {
        if (Objects.nonNull(sysUser)) {
            getData().setUser(sysUser);
        }
        if (Objects.nonNull(sysUserDetail)) {
            getData().setUserDetail(sysUserDetail);
        }
        if (StringUtils.isNotBlank(authorization)) {
            getData().setAuthorization(authorization);
        }
    }

    public static void clear() {
        LOCAL.remove();
    }

    public static boolean isLogin() {
        return Objects.nonNull(LOCAL.get())
                && StringUtils.isNotBlank(getContext().getAuthorization())
                && Objects.nonNull(getContext().getUser());
    }
}
